// i2s.cpp
// 该文件实现了 I2SFFTProcessor 类的功能，采用即时处理模式，不使用任何缓冲区。

#include "i2sfft.h"
#include "debug.h"
#include "config.h"
#include <ArduinoFFT.h>

// 替换 logError 和 logInfo
#undef logError
#undef logInfo

#define logError(fmt, ...) Serial.printf((String("[ERROR] ") + fmt + "\n").c_str(), ##__VA_ARGS__)
#define logInfo(fmt, ...) Serial.printf((String("[INFO] ") + fmt + "\n").c_str(), ##__VA_ARGS__)

// ==================== 构造函数和析构函数 ====================
I2SFFTProcessor::I2SFFTProcessor(uint16_t sampleCount, i2s_port_t i2sPort)
    : _sampleCount(sampleCount), _i2sPort(i2sPort)
{
}

I2SFFTProcessor::~I2SFFTProcessor()
{
    // 停止并卸载I2S驱动
    if (_i2sPort == I2S_NUM_0)
    {
        i2s_driver_uninstall(_i2sPort);
    }
}

// ==================== I2S初始化函数 ====================
bool I2SFFTProcessor::initialize()
{
    // I2S配置结构体
    i2s_config_t i2s_config = {
        .mode = (i2s_mode_t)(I2S_MODE_SLAVE | I2S_MODE_RX),
        .sample_rate = I2S_SAMPLE_RATE,
        .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
        .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
        .communication_format = I2S_COMM_FORMAT_STAND_I2S,
        .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
        .dma_buf_count = 8,
        .dma_buf_len = 1024,
        .use_apll = false,
        .tx_desc_auto_clear = false,
        .fixed_mclk = 0};

    // I2S引脚配置
    i2s_pin_config_t pin_config = {
        .bck_io_num = I2S_BCLK_PIN,
        .ws_io_num = I2S_LRCK_PIN,
        .data_out_num = I2S_PIN_NO_CHANGE,
        .data_in_num = I2S_DOUT_PIN};

    // 安装I2S驱动
    esp_err_t result = i2s_driver_install(_i2sPort, &i2s_config, 0, NULL);
    if (result != ESP_OK)
    {
        Serial.printf("[I2S错误] 安装I2S驱动失败: %d\n", result);
        return false;
    }

    // 设置I2S引脚
    result = i2s_set_pin(_i2sPort, &pin_config);
    if (result != ESP_OK)
    {
        Serial.printf("[I2S错误] 设置I2S引脚失败: %d\n", result);
        i2s_driver_uninstall(_i2sPort);
        return false;
    }

    // 启动I2S
    result = i2s_start(_i2sPort);
    if (result != ESP_OK)
    {
        Serial.printf("[I2S错误] 启动I2S失败: %d\n", result);
        i2s_driver_uninstall(_i2sPort);
        return false;
    }

    return true;
}

// ==================== 动态频段分配系统 ====================
void generateDynamicFrequencyBands(float *frequencies, int totalBands)
{
    // 从配置中获取各频段数量
    int bassBands = g_config.bassBands;       // 低频频段数量(20Hz-200Hz)
    int midBands = g_config.midBands;         // 中频频段数量(200Hz-2kHz)
    int highMidBands = g_config.highMidBands; // 中高频段数量(2kHz-10kHz)
    int highBands = g_config.highBands;       // 高频频段数量(10kHz-freqUpperLimit)

    // 计算配置的总频段数（这是实际的频段数，不受LED条数限制）
    int configTotalBands = bassBands + midBands + highMidBands + highBands;

    // 生成完整的频率数组（按配置的总频段数）
    float *fullFrequencies = new float[configTotalBands];
    int currentIndex = 0;

    // ==================== 生成低频频段 (20Hz-200Hz) ====================
    if (bassBands > 0)
    {
        float bassStart = 20.0f;
        float bassEnd = 200.0f;

        // 改用对数分布以确保频段间有足够差异
        float logStart = log10(bassStart);
        float logEnd = log10(bassEnd);
        float logStep = (logEnd - logStart) / bassBands;

        for (int i = 0; i < bassBands; i++)
        {
            float logFreq = logStart + i * logStep;
            fullFrequencies[currentIndex] = pow(10, logFreq);
            currentIndex++;
        }
    }

    // ==================== 生成中频频段 (200Hz-2kHz) ====================
    if (midBands > 0)
    {
        float midStart = 200.0f;
        float midEnd = 2000.0f;
        float midStep = (midEnd - midStart) / midBands;

        for (int i = 0; i < midBands; i++)
        {
            fullFrequencies[currentIndex] = midStart + i * midStep;
            currentIndex++;
        }
    }

    // ==================== 生成中高频段 (2kHz-10kHz) ====================
    if (highMidBands > 0)
    {
        float highMidStart = 2000.0f;
        float highMidEnd = 10000.0f;
        // 使用线性分布
        float highMidStep = (highMidEnd - highMidStart) / highMidBands;

        for (int i = 0; i < highMidBands; i++)
        {
            fullFrequencies[currentIndex] = highMidStart + i * highMidStep;
            currentIndex++;
        }
    }

    // ==================== 生成高频段 (10kHz-freqUpperLimit) ====================
    if (highBands > 0)
    {
        float highStart = 10000.0f;
        // 使用配置中的频率上限，而不是硬编码的20kHz
        float highEnd = (float)g_config.freqUpperLimit; // 从配置获取频率上限
        // 使用对数分布来更好地覆盖高频范围
        float logStart = log10(highStart);
        float logEnd = log10(highEnd);
        float logStep = (logEnd - logStart) / highBands;

        for (int i = 0; i < highBands; i++)
        {
            float logFreq = logStart + i * logStep;
            fullFrequencies[currentIndex] = pow(10, logFreq);
            currentIndex++;
        }
    }

    // ==================== 从完整频段中选取LED需要的频段 ====================
    if (totalBands >= configTotalBands)
    {
        // LED条数大于等于配置频段数，直接复制所有频段
        for (int i = 0; i < configTotalBands; i++)
        {
            frequencies[i] = fullFrequencies[i];
        }
        // 多余的LED条使用最后一个频段
        for (int i = configTotalBands; i < totalBands; i++)
        {
            frequencies[i] = fullFrequencies[configTotalBands - 1];
        }
    }
    else
    {
        // LED条数少于配置频段数，均匀选取
        for (int i = 0; i < totalBands; i++)
        {
            int sourceIndex = (i * configTotalBands) / totalBands;
            sourceIndex = min(sourceIndex, configTotalBands - 1);
            frequencies[i] = fullFrequencies[sourceIndex];
        }
    }

    // 清理临时数组
    delete[] fullFrequencies;
}

// 辅助函数：将频率转换为FFT bin
int freqToBin(float freq, int fftSize, int sampleRate)
{
    return (int)(freq * fftSize / sampleRate);
}

// ==================== 动态频段处理函数 ====================
float getFreqCompensationByBandIndex(int bandIndex, int totalBands)
{
    // 计算配置的总频段数
    int bassBands = g_config.bassBands;
    int midBands = g_config.midBands;
    int highMidBands = g_config.highMidBands;
    int highBands = g_config.highBands;
    int configTotalBands = bassBands + midBands + highMidBands + highBands;

    // 将LED频段索引映射回完整频段索引
    int sourceIndex;
    if (totalBands >= configTotalBands)
    {
        // LED条数大于等于配置频段数，直接使用索引
        sourceIndex = min(bandIndex, configTotalBands - 1);
    }
    else
    {
        // LED条数少于配置频段数，计算对应的源频段索引
        sourceIndex = (bandIndex * configTotalBands) / totalBands;
        sourceIndex = min(sourceIndex, configTotalBands - 1);
    }

    // 根据源频段索引确定属于哪个频段分组
    if (sourceIndex < bassBands)
    {
        return g_config.lowFreqComp; // 低频段
    }
    else if (sourceIndex < bassBands + midBands)
    {
        return g_config.midFreqComp; // 中频段
    }
    else if (sourceIndex < bassBands + midBands + highMidBands)
    {
        return g_config.highMidFreqComp; // 中高频段
    }
    else
    {
        return g_config.highFreqComp; // 高频段
    }
}

float getNoiseThresholdByBandIndex(int bandIndex, int totalBands)
{
    // 计算配置的总频段数
    int bassBands = g_config.bassBands;
    int midBands = g_config.midBands;
    int highMidBands = g_config.highMidBands;
    int highBands = g_config.highBands;
    int configTotalBands = bassBands + midBands + highMidBands + highBands;

    // 将LED频段索引映射回完整频段索引
    int sourceIndex;
    if (totalBands >= configTotalBands)
    {
        // LED条数大于等于配置频段数，直接使用索引
        sourceIndex = min(bandIndex, configTotalBands - 1);
    }
    else
    {
        // LED条数少于配置频段数，计算对应的源频段索引
        sourceIndex = (bandIndex * configTotalBands) / totalBands;
        sourceIndex = min(sourceIndex, configTotalBands - 1);
    }

    // 根据源频段索引确定属于哪个频段分组
    if (sourceIndex < bassBands)
    {
        return g_config.lowFreqNoise; // 低频段噪声阈值
    }
    else if (sourceIndex < bassBands + midBands)
    {
        return g_config.midFreqNoise; // 中频段噪声阈值
    }
    else if (sourceIndex < bassBands + midBands + highMidBands)
    {
        return g_config.highMidFreqNoise; // 中高频段噪声阈值
    }
    else
    {
        return g_config.highFreqNoise; // 高频段噪声阈值
    }
}

// ==================== 辅助函数实现 ====================
double I2SFFTProcessor::getSampleFromRaw(int32_t rawData)
{
    // 提取高24位
    int32_t sample = (rawData >> 8) & 0xFFFFFF;
    // 符号位扩展
    if (sample & 0x800000)
    {
        sample |= 0xFF000000;
    }
    // 归一化到 [-1.0, 1.0]
    return (double)sample / 8388608.0;
}

// ==================== 类成员函数实现 ====================

bool I2SFFTProcessor::readI2SData(double *leftBuffer, double *rightBuffer)
{
    // ==================== 重要说明 ====================
    // 此函数为即时读取模式，不使用任何内部缓冲区！
    // 每次调用都直接从I2S硬件读取最新数据
    // 请勿在此函数中添加任何形式的数据缓缓冲或存储逻辑
    // ================================================

    const int MAX_BUFFER_SIZE = 32;
    int32_t samples[64]; // 32对立体声样本 = 64个int32_t
    size_t bytesRead = 0;

    esp_err_t result = i2s_read(_i2sPort, samples, 64 * sizeof(int32_t), &bytesRead, 100);

    if (result != ESP_OK)
    {
        static uint32_t lastErrorTime = 0;
        uint32_t currentTime = millis();
        if (currentTime - lastErrorTime > 10000) // 减少错误日志频率
        {
            Serial.printf("[I2S错误] 读取失败: %d\n", result);
            lastErrorTime = currentTime;
        }

        if (bytesRead < 32 * sizeof(int32_t))
        {
            for (int i = 0; i < MAX_BUFFER_SIZE; i++)
            {
                leftBuffer[i] = 0.0;
                rightBuffer[i] = 0.0;
            }
            return false;
        }
    }

    int samplePairs = min(MAX_BUFFER_SIZE, (int)(bytesRead / sizeof(int32_t) / 2));
    for (int i = 0; i < samplePairs; i++)
    {
        double leftSample = getSampleFromRaw(samples[i * 2]);
        double rightSample = getSampleFromRaw(samples[i * 2 + 1]);

        leftBuffer[i] = isfinite(leftSample) ? leftSample : 0.0;
        rightBuffer[i] = isfinite(rightSample) ? rightSample : 0.0;
    }

    for (int i = samplePairs; i < MAX_BUFFER_SIZE; i++)
    {
        leftBuffer[i] = 0.0;
        rightBuffer[i] = 0.0;
    }

    return true;
}

// ==================== 修复：基于动态频段的FFT处理函数 ====================

/**
 * @brief 根据动态生成的频段计算FFT频段值
 * @param realPart FFT实部数据
 * @param bandIndex 动态频段索引 (0-总频段数)
 * @param frequencies 动态生成的频率数组
 * @param fftSize FFT大小
 * @param sampleRate 采样率
 * @return float FFT频段值
 */
float calculateDynamicFFTBandValue(double *realPart, int bandIndex, float *frequencies, int fftSize, int sampleRate)
{
    if (bandIndex < 0 || !frequencies)
    {
        return 0.0f;
    }

    // 获取当前频段的中心频率
    float centerFreq = frequencies[bandIndex];

    // 为所有频段使用特殊处理：直接基于频段索引分配不同的bin
    // 特殊处理：确保每个频段使用不同的bin
    int baseBin = 1 + bandIndex; // 从bin 1开始，每个频段递增
    int binRange = 2;            // 每个频段使用2个bin

    // 确保bin在有效范围内
    int startBin = constrain(baseBin, 1, fftSize / 2 - 1);
    int endBin = constrain(baseBin + binRange - 1, startBin, fftSize / 2 - 1);

    float totalValue = 0.0f;
    int binCount = 0;

    for (int bin = startBin; bin <= endBin; bin++)
    {
        totalValue += realPart[bin];
        binCount++;
    }

    return binCount > 0 ? (totalValue / binCount) : 0.0f;
}

// ==================== 修复：用动态频段替换原有的固定频段处理 ====================
bool I2SFFTProcessor::getInstantAudioBands(float *bandValues, int bandCount)
{
    if (!bandValues || bandCount <= 0)
    {
        return false;
    }

    // 初始化输出数组为0
    for (int i = 0; i < bandCount; i++)
    {
        bandValues[i] = 0.0f;
    }

    if (_i2sPort != I2S_NUM_0)
    {
        return false;
    }

    const int FFT_SIZE = SAMPLES;

    // 动态分配内存
    int32_t *i2sBuffer = new (std::nothrow) int32_t[FFT_SIZE];
    double *realPart = new (std::nothrow) double[FFT_SIZE];
    double *imagPart = new (std::nothrow) double[FFT_SIZE];
    float *dynamicFreqs = new (std::nothrow) float[bandCount];

    if (!i2sBuffer || !realPart || !imagPart || !dynamicFreqs)
    {
        Serial.printf("[内存错误] 无法分配FFT处理所需的内存\n");
        delete[] i2sBuffer;
        delete[] realPart;
        delete[] imagPart;
        delete[] dynamicFreqs;
        return false;
    }

    // 生成动态频段
    generateDynamicFrequencyBands(dynamicFreqs, bandCount);

    // I2S数据读取
    size_t bytesRead = 0;
    esp_err_t result = i2s_read(_i2sPort, i2sBuffer, FFT_SIZE * sizeof(int32_t), &bytesRead, 100);

    if (result != ESP_OK || bytesRead < FFT_SIZE * sizeof(int32_t))
    {
        delete[] i2sBuffer;
        delete[] realPart;
        delete[] imagPart;
        delete[] dynamicFreqs;

        static uint32_t lastErrLog = 0;
        if (millis() - lastErrLog > 5000)
        {
            Serial.printf("[FFT错误] I2S读取失败: result=%d, 期望=%d字节, 实际=%d字节\n",
                          result, FFT_SIZE * sizeof(int32_t), bytesRead);
            lastErrLog = millis();
        }
        return true;
    }

    // 音频增益处理
    float gainLinear = map(g_config.sensitivity, 10, 100, 5, 80) / 10.0f;
    float sensitivityNormalized = (g_config.sensitivity - 10) / 90.0f;
    float gainCurve = sensitivityNormalized * sensitivityNormalized;
    float gain = gainLinear * (0.7f + 0.3f * gainCurve);
    gain = constrain(gain, 0.3f, 10.0f);

    // DC偏移计算
    double leftDCOffset = 0.0;
    double rightDCOffset = 0.0;
    int samplesProcessed = bytesRead / sizeof(int32_t) / 2;

    if (samplesProcessed > 0)
    {
        for (int i = 0; i < samplesProcessed; i++)
        {
            leftDCOffset += getSampleFromRaw(i2sBuffer[i * 2]);
            rightDCOffset += getSampleFromRaw(i2sBuffer[i * 2 + 1]);
        }
        leftDCOffset /= samplesProcessed;
        rightDCOffset /= samplesProcessed;
    }

    // ==================== 自适应音量处理 ====================
    // 🔧 修复：优化自适应音量系统，提高静音检测准确性和增益调整响应性
    if (g_config.volumeAdaptive)
    {
        static float adaptiveGain = 1.0f;
        static float energyHistory[16] = {0}; // 增加到16帧历史，提高稳定性
        static uint8_t energyIndex = 0;
        static uint32_t silentFrameCount = 0; // 连续静音帧计数

        // 计算当前帧的能量 - 使用更多样本提高准确性
        double tempEnergy = 0.0;
        int sampleCount = min(samplesProcessed, 128); // 增加样本数量
        for (int i = 0; i < sampleCount; i++)
        {
            double leftSample = getSampleFromRaw(i2sBuffer[i * 2]) - leftDCOffset;
            double rightSample = getSampleFromRaw(i2sBuffer[i * 2 + 1]) - rightDCOffset;
            tempEnergy += fabs((leftSample + rightSample) / 2.0);
        }
        float currentAvgEnergy = tempEnergy / sampleCount;

        // 🔧 优化：动态调整静音检测阈值，考虑历史数据
        const float BASE_SILENCE_THRESHOLD = 0.0002f; // 基础静音阈值，提高到0.0002
        
        // 计算动态阈值：基于历史能量的最小值
        float minHistoryEnergy = 1.0f;
        for (int i = 0; i < 16; i++)
        {
            if (energyHistory[i] > 0 && energyHistory[i] < minHistoryEnergy)
            {
                minHistoryEnergy = energyHistory[i];
            }
        }
        
        // 动态静音阈值 = max(基础阈值, 历史最小值 * 1.5)
        float dynamicSilenceThreshold = max(BASE_SILENCE_THRESHOLD, minHistoryEnergy * 1.5f);
        
        // 🔧 优化：更准确的静音检测
        bool isCurrentlySilent = currentAvgEnergy < dynamicSilenceThreshold;
        
        if (isCurrentlySilent)
        {
            silentFrameCount++;
            
            // 连续静音超过一定帧数才开始重置增益
            if (silentFrameCount > 5) // 连续5帧静音才开始重置
            {
                // 🔧 优化：加快增益重置速度，避免长时间保持高增益
                const float RESET_SPEED = 0.15f; // 提高重置速度从0.05到0.15
                adaptiveGain = adaptiveGain * (1.0f - RESET_SPEED) + 1.0f * RESET_SPEED;
                
                static uint32_t lastAdaptiveSilenceDebug = 0;
                if (millis() - lastAdaptiveSilenceDebug > 3000) // 缩短调试输出间隔
                {
                    Serial.printf("[自适应静音] 连续静音%d帧，重置增益 - 当前能量:%.6f(动态阈值:%.6f), 增益:%.2f->1.0\n",
                                  silentFrameCount, currentAvgEnergy, dynamicSilenceThreshold, adaptiveGain);
                    lastAdaptiveSilenceDebug = millis();
                }
            }
        }
        else
        {
            // 非静音状态，重置静音帧计数
            silentFrameCount = 0;
            
            // 更新能量历史
            energyHistory[energyIndex] = currentAvgEnergy;
            energyIndex = (energyIndex + 1) % 16;

            // 计算历史平均能量（排除零值）
            float historicalAvgEnergy = 0.0f;
            int validSamples = 0;
            for (int i = 0; i < 16; i++)
            {
                if (energyHistory[i] > 0)
                {
                    historicalAvgEnergy += energyHistory[i];
                    validSamples++;
                }
            }
            if (validSamples > 0)
            {
                historicalAvgEnergy /= validSamples;
            }

            // 🔧 优化：动态目标能量水平
            const float TARGET_ENERGY_LOW = 0.05f;  // 低音量目标
            const float TARGET_ENERGY_HIGH = 0.15f; // 高音量目标
            
            // 根据当前能量水平选择目标
            float targetEnergy = (currentAvgEnergy < 0.01f) ? TARGET_ENERGY_LOW : TARGET_ENERGY_HIGH;

            // 🔧 优化：更敏感的增益调整
            if (historicalAvgEnergy > dynamicSilenceThreshold && validSamples >= 8)
            {
                float energyRatio = targetEnergy / historicalAvgEnergy;

                // 🔧 优化：根据能量变化幅度调整平滑系数
                float energyChange = fabs(currentAvgEnergy - historicalAvgEnergy) / historicalAvgEnergy;
                float gainSmoothing;
                
                if (energyChange > 0.5f)
                {
                    // 能量变化大时，使用更快的响应
                    gainSmoothing = 0.25f;
                }
                else if (energyChange > 0.2f)
                {
                    // 中等能量变化
                    gainSmoothing = 0.15f;
                }
                else
                {
                    // 能量变化小时，使用较慢的响应
                    gainSmoothing = 0.08f;
                }

                adaptiveGain = adaptiveGain * (1.0f - gainSmoothing) + energyRatio * gainSmoothing;

                // 🔧 优化：更严格的增益限制，防止过度放大
                adaptiveGain = constrain(adaptiveGain, 0.2f, 3.0f); // 降低最大增益从5.0到3.0

                static uint32_t lastAdaptiveDebug = 0;
                if (millis() - lastAdaptiveDebug > 2000)
                {
                    Serial.printf("[自适应音量] 当前能量=%.6f, 历史均值=%.6f(样本%d), 目标=%.2f, 自适应增益=%.2f, 最终增益=%.2f\n",
                                  currentAvgEnergy, historicalAvgEnergy, validSamples, targetEnergy, adaptiveGain, gain * adaptiveGain);
                    lastAdaptiveDebug = millis();
                }
            }
        }

        // 应用自适应增益到现有增益
        gain *= adaptiveGain;
    }

    // FFT数据准备
    for (int i = 0; i < FFT_SIZE; i++)
    {
        imagPart[i] = 0;
    }

    double rawAudioEnergy = 0;
    double maxSampleMagnitude = 0; // 新增：记录最大样本幅度用于更精确的静音检测
    
    for (int i = 0; i < samplesProcessed; i++)
    {
        double leftSample = (getSampleFromRaw(i2sBuffer[i * 2]) - leftDCOffset) * gain;
        double rightSample = (getSampleFromRaw(i2sBuffer[i * 2 + 1]) - rightDCOffset) * gain;

        realPart[i] = (leftSample + rightSample) / 2.0;
        rawAudioEnergy += fabs(realPart[i]);
        
        // 记录最大样本幅度
        double sampleMagnitude = fabs(realPart[i]);
        if (sampleMagnitude > maxSampleMagnitude)
        {
            maxSampleMagnitude = sampleMagnitude;
        }
    }

    for (int i = samplesProcessed; i < FFT_SIZE; i++)
    {
        realPart[i] = 0;
    }

    // ==================== 改进的静音检测 ====================
    double avgAudioEnergy = rawAudioEnergy / samplesProcessed;
    
    // 🔧 极大幅度降低静音检测阈值 - 使静音检测极其敏感
    const double SILENCE_THRESHOLD = 0.00000001;      // 进一步降低10倍，极其敏感
    const double MAX_SAMPLE_THRESHOLD = 0.0000001;    // 进一步降低10倍，极其敏感
    
    // 双重静音检测：平均能量 AND 最大样本幅度都必须低于阈值
    bool isSilent = (avgAudioEnergy < SILENCE_THRESHOLD) && (maxSampleMagnitude < MAX_SAMPLE_THRESHOLD);
    
    if (isSilent)
    {
        delete[] i2sBuffer;
        delete[] realPart;
        delete[] imagPart;
        delete[] dynamicFreqs;

        static uint32_t lastSilenceDebug = 0;
        if (millis() - lastSilenceDebug > 2000)
        {
            Serial.printf("[静音检测] 检测到静音 - 平均能量:%.12f(阈值:%.12f), 最大样本:%.9f(阈值:%.9f)\n",
                          avgAudioEnergy, SILENCE_THRESHOLD, maxSampleMagnitude, MAX_SAMPLE_THRESHOLD);
            lastSilenceDebug = millis();
        }
        
        // 静音状态下强制返回全零频段，确保LED完全关闭
        for (int i = 0; i < bandCount; i++)
        {
            bandValues[i] = 0.0f;
        }
        return true;
    }

    // FFT计算
    ArduinoFFT<double> FFT = ArduinoFFT<double>(realPart, imagPart, FFT_SIZE, I2S_SAMPLE_RATE);

    // 从全局配置获取窗函数类型，实现FFT窗函数平滑度的可配置
    FFTWindow windowType;
    switch (g_config.fftWindowType)
    {
    case 0:
        windowType = FFTWindow::Rectangle;
        break;
    case 1:
        windowType = FFTWindow::Hamming;
        break;
    case 2:
        windowType = FFTWindow::Hann;
        break;
    case 3:
        windowType = FFTWindow::Blackman;
        break;
    default:
        windowType = FFTWindow::Hamming;
        break; // 默认使用Hamming窗
    }

    FFT.windowing(windowType, FFTDirection::Forward);
    FFT.compute(FFTDirection::Forward);
    FFT.complexToMagnitude();

    // ==================== 更严格的FFT静音检测 ====================
    double fftTotalEnergy = 0.0;
    double fftMaxMagnitude = 0.0; // 新增：FFT最大幅度
    
    for (int i = 1; i < FFT_SIZE / 2; i++)
    {
        fftTotalEnergy += realPart[i];
        if (realPart[i] > fftMaxMagnitude)
        {
            fftMaxMagnitude = realPart[i];
        }
    }

    // 🔧 极大幅度降低FFT静音检测阈值，使其极其敏感
    const double FFT_SILENCE_THRESHOLD = 0.0001;        // 进一步降低10倍
    const double FFT_MAX_MAGNITUDE_THRESHOLD = 0.00005; // 进一步降低10倍
    
    // 双重FFT静音检测
    bool isFFTSilent = (fftTotalEnergy < FFT_SILENCE_THRESHOLD) && (fftMaxMagnitude < FFT_MAX_MAGNITUDE_THRESHOLD);
    
    if (isFFTSilent)
    {
        delete[] i2sBuffer;
        delete[] realPart;
        delete[] imagPart;
        delete[] dynamicFreqs;

        static uint32_t lastFFTSilenceDebug = 0;
        if (millis() - lastFFTSilenceDebug > 2000)
        {
            Serial.printf("[FFT静音检测] FFT能量过低 - 总能量:%.9f(阈值:%.9f), 最大幅度:%.9f(阈值:%.9f)\n",
                          fftTotalEnergy, FFT_SILENCE_THRESHOLD, fftMaxMagnitude, FFT_MAX_MAGNITUDE_THRESHOLD);
            lastFFTSilenceDebug = millis();
        }
        
        // FFT静音状态下强制返回全零频段
        for (int i = 0; i < bandCount; i++)
        {
            bandValues[i] = 0.0f;
        }
        return true;
    }

    // 动态频段处理
    float maxValue = 0.0f;
    float totalEnergy = 0.0f;
    int validBands = 0;

    // 第一遍：统计信息收集
    for (int i = 0; i < bandCount; i++)
    {
        float rawValue = calculateDynamicFFTBandValue(realPart, i, dynamicFreqs, FFT_SIZE, I2S_SAMPLE_RATE);

        // 应用频率补偿
        float freqCompensation = getFreqCompensationByBandIndex(i, bandCount);
        rawValue *= freqCompensation;

        // 应用噪声阈值过滤
        float noiseThreshold = getNoiseThresholdByBandIndex(i, bandCount);
        if (rawValue >= noiseThreshold)
        {
            totalEnergy += rawValue;
            maxValue = max(maxValue, rawValue);
            validBands++;
        }
    }

    // 动态归一化计算
    float dynamicNormFactor;
    if (maxValue > 0.0f)
    {
        float targetMax = g_config.spectrumCompression;
        dynamicNormFactor = targetMax / maxValue;
        dynamicNormFactor = constrain(dynamicNormFactor, 0.01f, 0.5f);
    }
    else
    {
        dynamicNormFactor = 0.05f;
    }

    // 第二遍：最终处理
    for (int i = 0; i < bandCount; i++)
    {
        float rawValue = calculateDynamicFFTBandValue(realPart, i, dynamicFreqs, FFT_SIZE, I2S_SAMPLE_RATE);

        float freqCompensation = getFreqCompensationByBandIndex(i, bandCount);
        float noiseThreshold = getNoiseThresholdByBandIndex(i, bandCount);

        rawValue *= freqCompensation;

        if (rawValue < noiseThreshold)
        {
            bandValues[i] = 0.0f;
            continue;
        }

        float finalValue = rawValue * dynamicNormFactor;
        finalValue = constrain(finalValue, 0.0f, 1.0f);

        // 🔧 大幅提高最终值过滤阈值，进一步减少微弱闪烁
        if (finalValue < 0.01f)  // 从0.003f提高到0.01f，更严格过滤
        {
            finalValue = 0.0f;
        }

        bandValues[i] = finalValue;
    }

    delete[] i2sBuffer;
    delete[] realPart;
    delete[] imagPart;
    delete[] dynamicFreqs;

    return true;
}

// ==================== 噪声检测接口 ====================
bool I2SFFTProcessor::isBufferReady() const
{
    return true; // 即时模式下始终准备好
}

bool I2SFFTProcessor::startNoiseDetection()
{
    return true; // 简化实现
}

bool I2SFFTProcessor::updateNoiseDetection()
{
    return true; // 简化实现
}

float I2SFFTProcessor::getNoiseLevel()
{
    return 0.0f; // 简化实现
}

// ==================== 节拍检测系统实现 ====================
// 节拍检测相关的全局变量
static float lastBeatEnergy = 0.0f;
static uint32_t lastBeatTime = 0;
static float beatEnergyHistory[16] = {0}; // 保存历史能量值用于计算平均值
static uint8_t beatHistoryIndex = 0;
static float currentBeatSignal = 0.0f;

/**
 * @brief 计算总体音频能量
 * @param bandValues 频段值数组
 * @param bandCount 频段数量
 * @return float 总体能量值
 */
float calculateTotalEnergy(float *bandValues, int bandCount)
{
    float totalEnergy = 0.0f;

    // 根据动态频段分配计算不同频段的加权能量
    int bassBands = g_config.bassBands;
    int midBands = g_config.midBands;
    int highMidBands = g_config.highMidBands;
    int highBands = g_config.highBands;
    int configTotalBands = bassBands + midBands + highMidBands + highBands;

    // 计算各频段在LED条中的索引范围
    int bassEndIndex, midEndIndex, highMidEndIndex;

    if (bandCount >= configTotalBands)
    {
        // LED条数大于等于配置频段数，直接使用配置值
        bassEndIndex = bassBands;
        midEndIndex = bassBands + midBands;
        highMidEndIndex = bassBands + midBands + highMidBands;
    }
    else
    {
        // LED条数少于配置频段数，按比例映射
        bassEndIndex = (bassBands * bandCount) / configTotalBands;
        midEndIndex = ((bassBands + midBands) * bandCount) / configTotalBands;
        highMidEndIndex = ((bassBands + midBands + highMidBands) * bandCount) / configTotalBands;
    }

    // 低音能量 (权重较高，因为节拍主要来自低频)
    for (int i = 0; i < bassEndIndex && i < bandCount; i++)
    {
        totalEnergy += bandValues[i] * 2.0f; // 低音权重x2
    }

    // 中音能量 (权重正常)
    for (int i = bassEndIndex; i < midEndIndex && i < bandCount; i++)
    {
        totalEnergy += bandValues[i] * 1.5f; // 中音权重x1.5
    }

    // 中高音能量 (权重较低)
    for (int i = midEndIndex; i < highMidEndIndex && i < bandCount; i++)
    {
        totalEnergy += bandValues[i] * 1.2f; // 中高音权重x1.2
    }

    // 高音能量 (权重最低)
    for (int i = highMidEndIndex; i < bandCount; i++)
    {
        totalEnergy += bandValues[i] * 0.8f; // 高音权重x0.8
    }

    return totalEnergy / bandCount; // 返回平均能量
}

/**
 * @brief 节拍检测算法
 * @param bandValues 频段值数组
 * @param bandCount 频段数量
 * @return bool 是否检测到节拍
 */
bool detectBeat(float *bandValues, int bandCount)
{
    uint32_t currentTime = millis();

    // 检查最小间隔，防止过度触发
    if (currentTime - lastBeatTime < g_config.beatMinInterval)
    {
        return false;
    }

    // 计算当前能量
    float currentEnergy = calculateTotalEnergy(bandValues, bandCount);

    // 更新能量历史
    beatEnergyHistory[beatHistoryIndex] = currentEnergy;
    beatHistoryIndex = (beatHistoryIndex + 1) % 16;

    // 计算历史平均能量
    float avgEnergy = 0.0f;
    for (int i = 0; i < 16; i++)
    {
        avgEnergy += beatEnergyHistory[i];
    }
    avgEnergy /= 16.0f;

    // 根据灵敏度调整阈值
    float sensitivityFactor = g_config.beatSensitivity / 100.0f;
    float dynamicThreshold = g_config.beatThreshold * (1.0f + sensitivityFactor);

    // 检测节拍：当前能量显著高于历史平均值
    bool beatDetected = false;
    if (currentEnergy > avgEnergy * dynamicThreshold && currentEnergy > 0.1f)
    {
        beatDetected = true;
        lastBeatTime = currentTime;

        // 设置节拍信号强度
        currentBeatSignal = g_config.beatBoostFactor;

        if (DEBUG_SERIAL)
        {
            Serial.printf("[节拍检测] 检测到节拍: 当前能量=%.2f, 平均能量=%.2f, 阈值=%.2f\n",
                          currentEnergy, avgEnergy, dynamicThreshold);
        }
    }

    // 节拍信号衰减
    if (currentBeatSignal > 0.0f)
    {
        currentBeatSignal *= (1.0f - g_config.beatDecayRate);
        if (currentBeatSignal < 0.01f)
        {
            currentBeatSignal = 0.0f;
        }
    }

    lastBeatEnergy = currentEnergy;
    return beatDetected;
}

/**
 * @brief 获取当前节拍信号强度（用于视觉增强）
 * @return float 节拍信号强度 (0.0-beatBoostFactor)
 */
float getCurrentBeatSignal()
{
    return currentBeatSignal;
}